package org.testile.datasetmanipulation;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.unitils.dbunit.datasetfactory.DataSetFactory;
import org.unitils.dbunit.util.MultiSchemaDataSet;

/**
 *
 * @author hvizmar
 * @author hudimar
 */
public class DynamicDataSetFactory implements DataSetFactory {

	private String defaultSchemaName;
	private DatasetWrapper sqlWrapper;
	private DatasetWrapper replaceWrapper;

	@Override
	public void init(Properties configuration, String defaultSchemaName) {
		this.defaultSchemaName = defaultSchemaName;
		sqlWrapper = getSQLWrapper(configuration);
		replaceWrapper = getReplaceWrapper(defaultSchemaName);
	}

	private DatasetWrapper getSQLWrapper(Properties configuration) {
		String driver = configuration.getProperty("database.driverClassName");
		String url = configuration.getProperty("database.url");
		String username = configuration.getProperty("database.userName");
		String password = configuration.getProperty("database.password");
		SQLEngineWrapper wrapper = new SQLEngineWrapper(driver,url,username,password);
		return wrapper;
	}
	
	private DatasetWrapper getReplaceWrapper(String defaultSchemaName) {
		Map<String,String> map = new HashMap<String, String>();
		map.put("schema", defaultSchemaName);
		ReplaceEngineWrapper wrapper = ReplaceEngineWrapper.of("DATABASE", map);
		return wrapper;
	}

	@Override
	public MultiSchemaDataSet createDataSet(File... dataSetFiles) {
		IDataSet dataset = loadDataSet(dataSetFiles[0]);
		IDataSet wrapped = sqlWrapper.wrap(replaceWrapper.wrap(dataset));
		MultiSchemaDataSet msds = new MultiSchemaDataSet();
		msds.setDataSetForSchema(defaultSchemaName, wrapped);
		return msds;
	}

	private IDataSet loadDataSet(File input) {
		try {
			return new XmlDataSet(new FileInputStream(input));
		} catch (FileNotFoundException ex) {
			throw new IllegalArgumentException("Could not load dataset from file [" + input + "]", ex);
		} catch (DataSetException ex) {
			throw new IllegalArgumentException("Could not load dataset from file [" + input + "]", ex);
		}
	}

	@Override
	public String getDataSetFileExtension() {
		return "xml";
	}
}
